﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GLLine2D
{
    public Vector2 from;
    public Vector2 to;
}

public class GLLine3D
{
    public Vector3 from;
    public Vector3 to;
    public Color color;
}

public class GLDraw
{

    public const int LINE = 1;
    public const int ARROW = 2;
    public const int ROTATE = 3;

    private Material lineMaterial;

    private Material LineMaterial
    {
        get
        {
            if (lineMaterial == null)
            {
                // Unity has a built-in shader that is useful for drawing
                // simple colored things.
                Shader shader = Shader.Find("Hidden/Internal-Colored");
                lineMaterial = new Material(shader);
                lineMaterial.hideFlags = HideFlags.HideAndDontSave;
                // Turn on alpha blending
                lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                // Turn backface culling off
                lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off);
                // Turn off depth writes
                lineMaterial.SetInt("_ZWrite", 0);
            }
            return lineMaterial;
        }
    }

    public void DrawLine3D(List<GLLine3D> lines, Transform centerAnchor, Color color)
    {
        GL.PushMatrix();

        LineMaterial.SetPass(0);

        if (centerAnchor != null)
        {
            GL.MultMatrix(centerAnchor.localToWorldMatrix);
        }

        GL.Begin(GL.LINES);

        for (int i = 0; i < lines.Count; i++)
        {
            GL.Color(lines[i].color);
            GL.Vertex(lines[i].from);
            GL.Vertex(lines[i].to);
        }

        GL.End();
        GL.PopMatrix();
    }

    public void DrawLine2D(List<GLLine2D> lines, Color color)
    {
        GL.PushMatrix();

        LineMaterial.SetPass(0);
        GL.LoadOrtho();
        GL.Color(color);

        // line
        GL.Begin(GL.LINES);

        for (int i = 0; i < lines.Count; i++)
        {
            GLLine2D line = lines[i];
            GL.Vertex3(line.from.x, line.from.y, 0);
            GL.Vertex3(line.to.x, line.to.y, 0);
        }

        GL.End();
        GL.PopMatrix();
    }

}
